﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace WindowsService
{
    public class LogHandle
    {
        public static void WriteErrorLog(Exception ex)
        {
            if (ex == null)
                return;

            StreamWriter writer = null;
            try
            {
                string logFile = "Log.log";
                string logPath = AppDomain.CurrentDomain.BaseDirectory;
                string log = logPath +"\\"+ logFile;

                if (!File.Exists(log))
                {
                    Directory.CreateDirectory(logPath);
                    writer = File.CreateText(log);
                }
                else
                {
                    writer = File.AppendText(log);
                }

                writer.WriteLine("Start-----------------" + DateTime.Now.ToString());
                writer.WriteLine("Method:" + ex.Source);
                writer.WriteLine("StackTrace:" + ex.StackTrace);
                writer.WriteLine("Message:" + ex.Message);
                writer.WriteLine("InnerException:" + ex.InnerException);
                writer.WriteLine("End-----------------" + DateTime.Now.ToString());

                writer.Flush();
                writer.Dispose();
            }
            catch
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
                return;
            }

        } 
    }
}
